<?php
/* -------------------------------------------------------------------------------------
* 	ID:						$Id: paypal.php 135 2013-09-22 07:30:55Z phone.mueller@googlemail.com $
* 	Letzter Stand:			$Revision: 135 $
* 	zuletzt geaendert von:	$Author: siekiera $
* 	Datum:					$Date: 2013-09-22 07:30:55 +0000 (Sun, 22 Sep 2013) $
*
* 	SEO:mercari by Siekiera Media
* 	http://www.seo-mercari.de
*
* 	Copyright (c) since 2011 SEO:mercari
* --------------------------------------------------------------------------------------
* 	based on:
* 	(c) 2000-2001 The Exchange Project  (earlier name of osCommerce)
* 	(c) 2002-2003 osCommerce - www.oscommerce.com
* 	(c) 2003     nextcommerce - www.nextcommerce.org
* 	(c) 2005     xt:Commerce - www.xt-commerce.com
*
* 	Released under the GNU General Public License
* ----------------------------------------------------------------------------------- */

class paypal {
	var $code, $title, $description, $enabled, $db;
	
	function __construct() {
		global $order, $db;
		
		$this->code = 'paypal';
		$this->title = MODULE_PAYMENT_PAYPAL_TEXT_TITLE;
		$this->description = MODULE_PAYMENT_PAYPAL_TEXT_DESCRIPTION;
		if(MODULE_PAYMENT_PAYPAL_SORT_ORDER!='')
			$this->sort_order = MODULE_PAYMENT_PAYPAL_SORT_ORDER;
		else
			$this->sort_order = 2;
		$this->enabled = ((MODULE_PAYMENT_PAYPAL_STATUS == 'True') ? true : false);
		$this->info = MODULE_PAYMENT_PAYPAL_TEXT_INFO;
		$this->order_status_success = PAYPAL_ORDER_STATUS_SUCCESS_ID;
		$this->order_status_rejected = PAYPAL_ORDER_STATUS_REJECTED_ID;
		$this->order_status_pending = PAYPAL_ORDER_STATUS_PENDING_ID;
		$this->order_status_tmp = PAYPAL_ORDER_STATUS_TMP_ID;
		$this->tmpOrders = false;
		$this->debug = true;
		$this->tmpStatus = PAYPAL_ORDER_STATUS_TMP_ID;
		$this->db = $db;
		if(is_object($order))
			$this->update_status();
	}
	
	function update_status() {
		
		global $order;
		if(($this->enabled == true) && ((int) MODULE_PAYMENT_PAYPAL_ZONE > 0)) {
			$check_flag = false;
			$check = $this->db->db_query("SELECT zone_id FROm ".TABLE_ZONES_TO_GEO_ZONES." WHERE geo_zone_id = '".MODULE_PAYMENT_PAYPAL_ZONE."' AND zone_country_id = '".$order->billing['country']['id']."' ORDER BY zone_id");
			while(!$check->EOF) {
				if($check->fields['zone_id'] < 1) {
					$check_flag = true;
					break;
				} elseif($check->fields['zone_id'] == $order->billing['zone_id']) {
					$check_flag = true;
					break;
				}
				$check->MoveNext();
			}
			if($check_flag == false)
				$this->enabled = false;
		}
	}

	function javascript_validation() {
		return false;
	}

	function selection() {
		return array('id' => $this->code, 'module' => $this->title, 'description' => $this->info);
	}

	function pre_confirmation_check() {
		return false;
	}

	function confirmation() {
		return array ('title' => $this->description);
	}

	function process_button() {
		return false;
	}

	function before_process() {
		if($_GET['PayerID']!='' AND $_SESSION['reshash']['TOKEN']!='' AND (strtoupper($_SESSION['reshash']["ACK"])=="SUCCESS" OR strtoupper($_SESSION['reshash']["ACK"])=="SUCCESSWITHWARNING"))
			return;
			
		global $order, $o_paypal;
		$o_paypal->paypal_auth_call();
		redirect($o_paypal->payPalURL.'&useraction=commit');
		return;
	}

	function payment_action() {
		global $order, $o_paypal, $tmp, $insert_id;
		$tmp = false;
		return;
	}

	function after_process() {
		global $order, $insert_id, $o_paypal;
		$o_paypal->complete_ceckout($insert_id, $_GET);
		$o_paypal->write_status_history($insert_id);
		$o_paypal->logging_status($insert_id);
		return;
	}

	function giropay_process() {
		global $o_paypal;
		$o_paypal->giropay_confirm($_GET);
		return;
	}

	function output_error() {
		return false;
	}

	function check() {
		if(!isset($this->_check)) {
			$check = $this->db->db_query("SELECT configuration_value FROM ".TABLE_CONFIGURATION." WHERE configuration_key = 'MODULE_PAYMENT_PAYPAL_STATUS'");
			$this->_check = $check->_numOfRows;
		}
		return $this->_check;
	}

	function admin_order($oID) {
		return false;
	}

	function install() {
		if(!defined('TABLE_PAYPAL'))
			define('TABLE_PAYPAL', DB_PREFIX.'paypal');

		if(!defined('TABLE_PAYPAL_STATUS_HISTORY'))
			define('TABLE_PAYPAL_STATUS_HISTORY', DB_PREFIX.'paypal_status_history');
		
		$stati = array('PAYPAL_INST_ORDER_STATUS_TMP_NAME' => 'PAYPAL_INST_ORDER_STATUS_TMP_ID',
						'PAYPAL_INST_ORDER_STATUS_SUCCESS_NAME' => 'PAYPAL_INST_ORDER_STATUS_SUCCESS_ID',
						'PAYPAL_INST_ORDER_STATUS_PENDING_NAME' => 'PAYPAL_INST_ORDER_STATUS_PENDING_ID',
						'PAYPAL_INST_ORDER_STATUS_REJECTED_NAME' => 'PAYPAL_INST_ORDER_STATUS_REJECTED_ID');
		foreach($stati AS $statusname => $statusid) {
			$languages = $this->db->db_query("SELECT * FROM ".TABLE_LANGUAGES." ORDER BY sort_order");
			while(!$languages->EOF) {
				if(file_exists(DIR_FS_LANGUAGES.$languages->fields['directory'].'/admin/paypal.php'))
					include(DIR_FS_LANGUAGES.$languages->fields['directory'].'/admin/paypal.php');
				if($$statusname!=''){
					$status = $this->db->db_query("SELECT orders_status_id FROM ".TABLE_ORDERS_STATUS." WHERE orders_status_name = '" .$statusname. "' AND language_id='".$languages->fields['languages_id']."' limit 1");
					
					if(!$check->_numOfRows OR ($$statusid AND $status->fields['orders_status_id'] !=$$statusid)){
						if(!$$statusid) {
							$status = $this->db->db_query("SELECT max(orders_status_id) as status_id from ".TABLE_ORDERS_STATUS);
							$$statusid = $status->fields['status_id']+1;
						}
						$check = $this->db->db_query("SELECT orders_status_id FROM ".TABLE_ORDERS_STATUS." WHERE orders_status_id = '".$$statusid ."' AND language_id='".$languages->fields['languages_id']."'");
						if($check->_numOfRows < 1)
							$this->db->db_query("INSERT INTO ".TABLE_ORDERS_STATUS." (orders_status_id, language_id, orders_status_name) VALUES ('".$$statusid."', '".$languages->fields['languages_id']."', '" .$$statusname. "')");

					} else
						$$statusid = $status->fields['orders_status_id'];
				}
				$languages->MoveNext();
			}
		}
		$m_fields=' (configuration_key, configuration_value, configuration_group_id, sort_order, last_modified, date_added, use_function, set_function) ';

		$this->db->db_query("INSERT INTO ".TABLE_CONFIGURATION.$m_fields."values ('MODULE_PAYMENT_PAYPAL_STATUS', 'True', '6', '3', NULL, NOW(), '', 'cfg_select_option(array(\'True\', \'False\'),' )");
		$this->db->db_query("INSERT INTO ".TABLE_CONFIGURATION.$m_fields."values ('MODULE_PAYMENT_PAYPAL_SORT_ORDER', '0', '6', '0', NULL, NOW(), '', '')");
		$this->db->db_query("INSERT INTO ".TABLE_CONFIGURATION.$m_fields."values ('MODULE_PAYMENT_PAYPAL_ALLOWED', '', '6', '0', NULL, NOW(), '', '')");
		$this->db->db_query("INSERT INTO ".TABLE_CONFIGURATION.$m_fields."values ('MODULE_PAYMENT_PAYPAL_ZONE', '0', '6', '2', NULL, NOW(), 'get_zone_class_title', 'cfg_pull_down_zone_classes(')");
		
		$rest_values = $this->db->db_query("select * from ".TABLE_CONFIGURATION." where configuration_key like 'PAYPAL\_%'");
		$rest_array = array();
		while(!$rest_values->EOF) {
			$rest_array[] = $rest_values->fields;
			$rest_values->MoveNext();
		}

		$this->db->db_query("DELETE FROM ".TABLE_CONFIGURATION." WHERE configuration_key LIKE 'PAYPAL\_%'");

		$new_config   = array();
		$new_config[] = array('','PAYPAL_MODE', 'live', 27, 1, '', 'cfg_select_option(array("live", "sandbox"),');
		$new_config[] = array('','PAYPAL_API_USER', '', 27, 2, '', '');
		$new_config[] = array('','PAYPAL_API_PWD', '', 27, 3, '', '');
		$new_config[] = array('','PAYPAL_API_SIGNATURE', '', 27, 4, '', '');
		$new_config[] = array('','PAYPAL_API_SANDBOX_USER', '', 27, 5, '', '');
		$new_config[] = array('','PAYPAL_API_SANDBOX_PWD', '', 27, 6, '', '');
		$new_config[] = array('','PAYPAL_API_SANDBOX_SIGNATURE', '', 27, 7, '', '');
		$new_config[] = array('','PAYPAL_ORDER_STATUS_TMP_ID', (($PAYPAL_INST_ORDER_STATUS_TMP_ID)?$PAYPAL_INST_ORDER_STATUS_TMP_ID:'1'), 27, 9, 'get_order_status_name', 'cfg_pull_down_order_statuses(');
		$new_config[] = array('','PAYPAL_ORDER_STATUS_SUCCESS_ID', (($PAYPAL_INST_ORDER_STATUS_SUCCESS_ID)?$PAYPAL_INST_ORDER_STATUS_SUCCESS_ID:'2'), 27, 10, 'get_order_status_name', 'cfg_pull_down_order_statuses(');
		$new_config[] = array('','PAYPAL_ORDER_STATUS_PENDING_ID', (($PAYPAL_INST_ORDER_STATUS_PENDING_ID)?$PAYPAL_INST_ORDER_STATUS_PENDING_ID:'5'), 27, 11, 'get_order_status_name', 'cfg_pull_down_order_statuses(');
		$new_config[] = array('','PAYPAL_ORDER_STATUS_REJECTED_ID',(($PAYPAL_INST_ORDER_STATUS_REJECTED_ID)?$PAYPAL_INST_ORDER_STATUS_REJECTED_ID:'4'), 27, 12, 'get_order_status_name', 'cfg_pull_down_order_statuses(');
		$new_config[] = array('','PAYPAL_COUNTRY_MODE', 'de', 27, 16, '', 'cfg_select_option(array("de", "uk"),');
		$new_config[] = array('','PAYPAL_EXPRESS_ADDRESS_CHANGE', 'true', 27, 17, '', 'cfg_select_option(array("true", "false"),');
		$new_config[] = array('','PAYPAL_EXPRESS_ADDRESS_OVERRIDE', 'true', 27, 18, '', 'cfg_select_option(array("true", "false"),');
		$new_config[] = array('','PAYPAL_API_VERSION', '72.0', 27, 20, '', '');
		$new_config[] = array('','PAYPAL_API_IMAGE', 'shop_logo.jpg', 27, 21,  '', '');
		$new_config[] = array('','PAYPAL_API_CO_BACK', '', 27, 22, '', '');
		$new_config[] = array('','PAYPAL_API_CO_BORD', '', 27, 23, '', '');
		$new_config[] = array('','PAYPAL_ERROR_DEBUG', 'false', 27, 24, '', 'cfg_select_option(array("true", "false"),');
		$new_config[] = array('','PAYPAL_INVOICE', '', 27, 25, '', '');
		$new_config[] = array('','PAYPAL_EXP_VERS', '', 27, 26, '', '');
		$new_config[] = array('','PAYPAL_API_KEY', '120,116,99,111,109,109,101,114,99,101,95,83,104,111,112,112,105,110,103,67,97,114,116,95', 6, 5, '', '');

		foreach($new_config AS $v1) {
			$old_config = $this->mn_confsearch($v1[1], $rest_array);
			$this->db->db_query("INSERT INTO 
									".TABLE_CONFIGURATION.$m_fields."
								VALUES 
									('".(($old_config)?$old_config[1]:$v1[1])."', 
									'".(($old_config)?$old_config[2]:$v1[2])."', 
									".(($old_config)?$old_config[3]:$v1[3]).", 
									".$v1[4].", 
									NULL, 
									NOW(), 
									'".$v1[5]."',
									'".$v1[6]."')");
		}

		$this->db->db_query("UPDATE ".TABLE_CONFIGURATION." SET configuration_value = '72.0' WHERE configuration_key = 'PAYPAL_API_VERSION'");
		$this->db->db_query("UPDATE ".TABLE_CONFIGURATION." SET configuration_value = 'False' WHERE configuration_key = 'SESSION_CHECK_USER_AGENT'");
		$this->db->db_query("UPDATE ".TABLE_CONFIGURATION." SET configuration_value = 'False' WHERE configuration_key = 'SESSION_CHECK_IP_ADDRESS'");
		
		$check = $this->db->db_query("SELECT configuration_group_title FROM ".TABLE_CONFIGURATION_GROUP." WHERE configuration_group_title = 'PayPal'");
		if(!$check->_numOfRows) {
			$m_fields=' (configuration_group_id, configuration_group_title, configuration_group_description, sort_order, visible) ';
			$this->db->db_query("INSERT INTO ".TABLE_CONFIGURATION_GROUP.$m_fields."VALUES (27, 'PayPal', 'PayPal', 27, 1 )");
		}
		
		$check = $this->db->db_query("SHOW COLUMNS FROM ".TABLE_ADDRESS_BOOK." LIKE 'address\_class'");
		if(!$check->_numOfRows)
			$this->db->db_query("ALTER TABLE ".TABLE_ADDRESS_BOOK." ADD address_class VARCHAR(32) NOT NULL");
		else
			$this->db->db_query("ALTER TABLE ".TABLE_ADDRESS_BOOK." MODIFY address_class VARCHAR(32) NOT NULL");

		$m_fields = "paypal_ipn_id int(11) unsigned NOT NULL auto_increment, order_id int(11) unsigned NOT NULL default '0', txn_type varchar(32) NOT NULL default '', reason_code varchar(15) default NULL, payment_type varchar(7) NOT NULL default '', payment_status varchar(17) NOT NULL default '', pending_reason varchar(14) default NULL, invoice varchar(64) default NULL, mc_currency char(3) NOT NULL default '', first_name varchar(32) NOT NULL default '', last_name varchar(32) NOT NULL default '', payer_business_name varchar(64) default NULL, address_name varchar(32) default NULL, address_street varchar(64) default NULL, address_city varchar(32) default NULL, address_state varchar(32) default NULL, address_zip varchar(10) default NULL, address_country varchar(64) default NULL, address_status varchar(11) default NULL, payer_email varchar(96) NOT NULL default '', payer_id varchar(32) NOT NULL default '', payer_status varchar(10) NOT NULL default '', payment_date datetime NOT NULL default '0001-01-01 00:00:00', business varchar(96) NOT NULL default '', receiver_email varchar(96) NOT NULL default '', receiver_id varchar(32) NOT NULL default '', txn_id varchar(40) NOT NULL default '', parent_txn_id varchar(17) default NULL, num_cart_items tinyint(4) unsigned NOT NULL default '1', mc_gross decimal(7,2) NOT NULL default '0.00', mc_fee decimal(7,2) NOT NULL default '0.00', mc_shipping decimal(7,2) NOT NULL default '0.00', payment_gross decimal(7,2) default NULL, payment_fee decimal(7,2) default NULL, settle_amount decimal(7,2) default NULL, settle_currency char(3) default NULL, exchange_rate decimal(4,2) default NULL, notify_version decimal(2,1) NOT NULL default '0.0', verify_sign varchar(128) NOT NULL default '', last_modified datetime NOT NULL default '0001-01-01 00:00:00', date_added datetime NOT NULL default '0001-01-01 00:00:00', memo text, mc_authorization decimal(7,2) NOT NULL, mc_captured decimal(7,2) NOT NULL";
		$db_installed = false;

		$tables = $this->db->db_query("SHOW TABLES LIKE '".TABLE_PAYPAL."'");
		if(!$tables->_numOfRows)
			$this->db->db_query("CREATE TABLE ".TABLE_PAYPAL." (".$m_fields.", PRIMARY KEY (paypal_ipn_id, txn_id), KEY order_id (order_id))");
		else
			$this->db->db_query("ALTER TABLE ".TABLE_PAYPAL." MODIFY ".str_replace(', ',', MODIFY ',$m_fields));

		$m_fields = "payment_status_history_id int(11) NOT NULL auto_increment, paypal_ipn_id int(11) NOT NULL default '0', txn_id varchar(64) NOT NULL default '', parent_txn_id varchar(64) NOT NULL default '', payment_status varchar(17) NOT NULL default '', pending_reason varchar(64) default NULL, mc_amount decimal(7,2) NOT NULL, date_added datetime NOT NULL default '0001-01-01 00:00:00'";
		
		$tables = $this->db->db_query("SHOW TABLES LIKE '".TABLE_PAYPAL_STATUS_HISTORY."'");
		if(!$tables->_numOfRows)
			$this->db->db_query("CREATE TABLE ".TABLE_PAYPAL_STATUS_HISTORY." (".$m_fields.", PRIMARY KEY (payment_status_history_id), KEY paypal_ipn_id (paypal_ipn_id) )");
		else
			$this->db->db_query("ALTER TABLE ".TABLE_PAYPAL_STATUS_HISTORY." MODIFY ".str_replace(', ',', MODIFY ',$m_fields));

		$check_admin = $this->db->db_query("SELECT mID FROM ".DB_PREFIX."admin_menu WHERE menu_name = 'paypal'");
		if(!$check_admin->_numOfRows) {
			$this->db->db_query("INSERT INTO ".DB_PREFIX."admin_menu (menu_name, group_id, parent_id, sort_order, visible, link, title_language_id_1) VALUES ('paypal', 0, 9, 5, 1, 1, 'Paypal')");
			$this->db->db_query("INSERT INTO ".DB_PREFIX."admin_menu (menu_name, group_id, parent_id, sort_order, visible, link, title_language_id_1) VALUES ('configuration', 27, 12, 1, 1, 1, 'Paypal - Konfiguration')");
			$this->db->db_query("INSERT INTO ".DB_PREFIX."admin_access_rights (file_name, g_1) VALUES ('paypal', 1)");
			$this->db->db_query("INSERT INTO ".DB_PREFIX."admin_access_rights (file_name, g_1) VALUES ('configuration-27', 1)");
		}
	}

	function remove($pre_inst=0) {
		if(!defined('TABLE_PAYPAL'))
			define('TABLE_PAYPAL', DB_PREFIX.'paypal');
			
		if(!defined('TABLE_PAYPAL_STATUS_HISTORY'))
			define('TABLE_PAYPAL_STATUS_HISTORY', DB_PREFIX.'paypal_status_history');
			
		if(!$_POST['paypaldelete'] AND !$pre_inst){
			$check = $this->db->db_query("SELECT configuration_key FROM ".TABLE_CONFIGURATION." WHERE configuration_key = 'MODULE_PAYMENT_PAYPALEXPRESS_STATUS'");
			if(!$check->_numOfRows)
				redirect(href_link('modules_payment.php', 'set='.$_GET['set'].'&module='.$this->code.'&action=removepaypal'));
		}
		
		$this->db->db_query("DELETE FROM ".TABLE_CONFIGURATION." WHERE configuration_key like 'MODULE_PAYMENT_PAYPAL_%'");

		$check = $this->db->db_query("SELECT configuration_key FROM ".TABLE_CONFIGURATION." WHERE configuration_key = 'MODULE_PAYMENT_PAYPALEXPRESS_STATUS'");
		if(!$check->_numOfRows){
			$this->db->db_query("DELETE FROM ".TABLE_CONFIGURATION." WHERE configuration_key like 'PAYPAL\_%'");
			$this->db->db_query("DELETE FROM ".TABLE_CONFIGURATION_GROUP." WHERE configuration_group_title = 'PayPal'");
			$this->db->db_query("DELETE FROM ".DB_PREFIX."admin_menu WHERE menu_name = 'paypal'");
			$this->db->db_query("DELETE FROM ".DB_PREFIX."admin_menu  WHERE menu_name = 'configuration' AND group_id = '27'");
			$this->db->db_query("DELETE FROM ".DB_PREFIX."admin_access_rights WHERE file_name = 'paypal'");
			$this->db->db_query("DELETE FROM ".DB_PREFIX."admin_access_rights WHERE file_name = 'configuration-27'");
			$this->db->db_query("DROP TABLE IF EXISTS ".TABLE_PAYPAL);
			$this->db->db_query("DROP TABLE IF EXISTS ".TABLE_PAYPAL_STATUS_HISTORY);
		}
	}

	function keys() {
		return array('MODULE_PAYMENT_PAYPAL_STATUS', 
					'MODULE_PAYMENT_PAYPAL_ALLOWED', 
					'MODULE_PAYMENT_PAYPAL_ZONE',
					'MODULE_PAYMENT_PAYPAL_SORT_ORDER');
	}
	
	function mn_confsearch($needle, $haystack ){
		foreach($haystack as $key1 => $value1){
			if(is_array($value1)) {
				$nodes = array_search($needle, $value1);
				if($nodes){
					$old_config=array();
					foreach($value1 as $key2 => $value2)
						$old_config[] = $value2;

					return($old_config);
				}
			}
		}
		return;
	}
}
?>